<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">

      <el-form-item label="字典名称" prop="dictCode">
        <el-select v-model="queryParams.dictCode" size="small">
          <el-option v-for="item in dictOptions" :key="item.id" :label="item.name" :value="item.code"/>
        </el-select>
      </el-form-item>

      <el-form-item label="元素标签" prop="label">
        <el-input v-model="queryParams.label" placeholder="元素标签" clearable size="small"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="元素状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label"
                     :value="+dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPerm="['sys:dict:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPerm="['sys:dict:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPerm="['sys:dict:remove']">删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" :height="tableHeight">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="50" align="center"/>
      <el-table-column label="字典编码" align="center" prop="dictCode"/>
      <el-table-column label="元素标签" align="center" prop="label"/>
      <el-table-column label="元素键值" align="center" prop="value"/>
      <el-table-column label="图片" align="center" prop="img" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.img==''|| scope.row.img == undefined">暂无</span>
          <el-image v-else :src="scope.row.img" style="width: 80px; height: 80px" fit="fill"
                    :preview-src-list="[scope.row.img]"/>
        </template>
      </el-table-column>
      <el-table-column label="元素排序" align="center" prop="sort"/>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="创建时间" align="center" prop="gmtCreate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPerm="['sys:dict:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPerm="['sys:dict:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页插件-->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
                @pagination="getList"/>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="元素标签" prop="label">
          <el-input v-model="form.label" placeholder="请输入元素标签"/>
        </el-form-item>
        <el-form-item label="元素键值" prop="value">
          <el-input v-model="form.value" placeholder="请输入元素键值"/>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload class="up-img-uploader" :action="imageAction" :show-file-list="false"
                     :on-success="handleUploadSuccess" :headers="headers">
            <img v-if="imageUrl" :src="imageUrl" class="up-img" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.value" :label="+dict.value">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDictItem, getDictItem, delDictItem, addDictItem, updateDictItem } from '@a/sys/dictItem'
import { getDict, getDictByCode, getOptionSelect } from '@a/sys/dict'
import { getToken } from '@u/auth'

export default {
  name: 'Data',
  data() {
    return {
      headers: {
        // 上传文件的请求头
        Authorization: 'Bearer ' + getToken()
      },
      imageUrl: null, // 上传图片回显
      // 新闻封面请求地址
      imageAction: process.env.VUE_APP_BASE_API + process.env.VUE_APP_FILE_UPLOAD, // 上传的图片服务器地址
      tableHeight: window.innerHeight - 340,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      list: [],
      // 默认字典编码
      defaultDictCode: '',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 字典数据字典
      dictOptions: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        label: undefined,
        dictCode: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        label: [
          { required: true, message: '字典元素标签不能为空', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '字典元素键值不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '字典元素顺序不能为空', trigger: 'blur' }
        ]
      },
      dictId: undefined
    }
  },
  created() {
    this.dictId = this.$route.params && this.$route.params.dictId
    this.getDict(this.dictId)
    this.getDictList()
    this.getDictItems('sys_normal_disable').then(response => {
      // console.log('statusOptions', response.data)
      this.statusOptions = response.data
    })
  },
  methods: {
    /** 上传封面成功 **/
    handleUploadSuccess(res, file) {
      // console.log(res)
      if (res.code == 200) {
        const { url } = res.data
        this.msgNoticeSuccess('上传成功')
        // console.log(url)
        this.imageUrl = url
        this.form.img = url
      }
    },
    /** 查询字典详细 */
    getDict(dictId) {
      getDict(dictId).then(response => {
        this.queryParams.dictCode = response.data.code
        this.defaultDictCode = response.data.code
        this.getList()
      })
    },
    /** 查询字典列表 */
    getDictList() {
      getOptionSelect().then(response => {
        console.log(response.data)
        this.dictOptions = response.data
      })
    },
    /** 查询字典数据列表 */
    getList() {
      this.loading = true
      listDictItem(this.queryParams).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    // 数据状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        label: undefined,
        img: undefined,
        value: undefined,
        sort: 0,
        status: 0,
        remark: undefined
      }
      this.imageUrl = null
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.dictCode = this.defaultDictCode
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加字典元素'
      // 先查询出当前显示的字典编码列表
      getDictByCode(this.queryParams.dictCode).then(response => {
        this.form.dictId = response.data.id
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictCode)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const dictItemId = row.id || this.ids
      getDictItem(dictItemId).then(response => {
        this.form = response.data
        // 回显图片
        this.imageUrl = this.form.img
        this.open = true
        this.title = '修改字典元素'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateDictItem(this.form).then(response => {
              this.msgNoticeSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addDictItem(this.form).then(response => {
              this.msgNoticeSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictItemIds = row.id || this.ids
      this.$confirm('是否确认删除元素编号为"' + dictItemIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delDictItem(dictItemIds)
      }).then(() => {
        this.getList()
        this.msgNoticeSuccess('删除成功')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.up-img-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #000000;
  background-color: #e8e8e8;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.up-img {
  width: 200px;
  height: 200px;
  display: block;
}

.dialog-banner ::v-deep .el-dialog__body {
  height: 520px;

  .el-dialog {
    height: 87%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    padding-left: 15px;
  }
}
</style>
